package com.example.nftapp.wdg;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.example.nftapp.R;
import com.example.nftapp.utils.TimeUtil;

/**
 * 封装CustomCustomVideoView，以便复用
 */
public class CustomVideoView extends ConstraintLayout {

    private VideoView vv;
    private ImageView ivPlayOrPause;
    private TextView tvTimeProgress, tvTimeTotal;
    private SeekBar sbVideoProgress;
    private MediaPlayer mMediaPlayer;

    /**
     * 刷新进度的Runnable
     */
    private final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            refreshProgress();
            postDelayed(runnable, 1000);
        }
    };

    /**
     * 构造函数
     *
     * @param context
     * @param attrs
     */
    public CustomVideoView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
        TypedArray a = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.CustomVideoView, 0, 0);
        tvTimeProgress.setTextColor(a.getColor(R.styleable.CustomVideoView_fontColor, Color.WHITE));
        tvTimeProgress.setTextSize(a.getDimension(R.styleable.CustomVideoView_fontSize, 14));
    }

    /**
     * 构造函数
     *
     * @param context
     */
    public CustomVideoView(@NonNull Context context) {
        super(context);
        initView(context);
    }

    /**
     * 对外界暴露设置视频资源的方法
     *
     * @param uri
     */
    public void setVideoUri(Uri uri) {
        vv.setVideoURI(uri);
    }

    /**
     * 挂起操作，回收资源
     */
    public void suspend() {
        vv.suspend();
        removeCallbacks(runnable);
    }

    /**
     * 初始化自定义组件CustomVideoView
     *
     * @param context
     */
    private void initView(Context context) {
        // 设置CustomVideoView的布局文件
        LayoutInflater.from(context).inflate(R.layout.layout_custom_video_view, this, true);
        // 初始化组件
        vv = findViewById(R.id.videoView);
        ivPlayOrPause = findViewById(R.id.ivPlayOrPause);
        tvTimeProgress = findViewById(R.id.tvTimeProgress);
        tvTimeTotal = findViewById(R.id.tvTimeTotal);
        sbVideoProgress = findViewById(R.id.sbVideoProgress);
        // 设置监听事件
        vv.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                // 视频播放前的准备
                mMediaPlayer = mediaPlayer;
                int videoDuration = mMediaPlayer.getDuration();// 毫秒，时长60140毫秒
                sbVideoProgress.setMax(videoDuration);// 设置SeekBar最大值
                tvTimeTotal.setText(TimeUtil.millTimeToStrTime(videoDuration));
                doPlayOrPause(false);
                post(runnable);
            }
        });
        vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                // 视频播放完成的处理
                doPlayOrPause(true);
            }
        });
        ivPlayOrPause.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                // 点击ivPlayOrPause 切换播放/暂停
                doPlayOrPause(mMediaPlayer.isPlaying());
            }
        });
        sbVideoProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if (b) {
                    // b为true表示人为调整进度，那么MediaPlayer需要跟着变化播放进度
                    mMediaPlayer.seekTo(i);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    /**
     * 执行暂停、播放操作
     *
     * @param isPlaying true表示正在播放，执行暂停操作
     *                  false表示未在播放，执行播放操作
     */
    private void doPlayOrPause(boolean isPlaying) {
        if (isPlaying) {
            mMediaPlayer.pause();
            ivPlayOrPause.setImageResource(R.mipmap.play_btn_play);
        } else {
            mMediaPlayer.start();
            ivPlayOrPause.setImageResource(R.mipmap.play_btn_pause_prs);
        }
    }

    /**
     * 刷新播放进度
     */
    @SuppressLint("DefaultLocale")
    private void refreshProgress() {
        int currentPosition = mMediaPlayer.getCurrentPosition();// 获取播放进度，毫秒，时长60140毫秒
        sbVideoProgress.setProgress(currentPosition);
        tvTimeProgress.setText(TimeUtil.millTimeToStrTime(currentPosition));
    }

}
